﻿/*
*类名：MenuClickEventDeal
*归属：QinMing.Weixin.EventHandlerMenuClick命名空间
*用途：处理微信用户点击菜单触发的click事件，并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.00.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using QinMing.Config;
using QinMing.Tools;
using QinMing.Weixin.ReturnContent;

namespace QinMing.Weixin.EventHandlerMenuClick
{
	//事件消息处理：点击菜单click
    public class MenuClickEventDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealMenuClick(weixinXML);  
            return content;
        }

        public string DealMenuClick(string weixinXML)
        {
            string strresponse = "";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType=xn.SelectSingleNode("//MsgType").InnerText;
            string Event=xn.SelectSingleNode("//Event").InnerText;
			string EventKey=xn.SelectSingleNode("//EventKey").InnerText;
			
			//保存点击菜单click事件
			SaveEvent(FromUserName, ToUserName, EventKey);
			
			if(EventKey == "14")
			{
				//菜单自定义键值11的处理
				ReturnMsg rm = new ReturnMsg();
				strresponse = rm.ReturnText(FromUserName, ToUserName, "您刚点击的菜单键值为" + EventKey);
			}
			
            //给管理员发送粉丝点击菜单通知
			QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "粉丝点击菜单信息提醒" + FromUserName, "http://www.yourweb.com/Weixin/DisplayOneUser.aspx?open_id=" + FromUserName);  
			
			return strresponse;
        }
		
		//保存事件信息
        public void SaveEvent(string FromUserName, string ToUserName,string EventKey)
        {
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into weixin_recv_event (msg_type,event_type,open_id,gh_id,recv_time,event_key) "
			    + "values ('event','CLICK','" + FromUserName + "','" + ToUserName + "',getdate(),'" + EventKey + "') ";
            //QinMingTools.WriteLog("sql语句：", cmd.CommandText);
			cmd.ExecuteScalar();
      
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }

    }
}